'use client';

import type Uppy from '@uppy/core';
import type { HTMLAttributes, ReactNode } from 'react';
import { useRef, useState } from 'react';

export function Dropzone({
  uppy,
  children,
  ...divProps
}: {
  uppy: Uppy;
  children: (dragging: boolean) => ReactNode | ReactNode;
} & Omit<HTMLAttributes<HTMLDivElement>, 'children'>) {
  const [dragging, setdragging] = useState(false);
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  return (
    <div
      {...divProps}
      onDragEnter={(e) => {
        e.preventDefault();
        setdragging(true);
      }}
      onDragLeave={(e) => {
        e.preventDefault();
        if (timerRef.current) {
          clearTimeout(timerRef.current);
          timerRef.current = null;
        }
        timerRef.current = setTimeout(() => {
          setdragging(false);
        }, 50);
      }}
      onDragOver={(e) => {
        e.preventDefault();
        if (timerRef.current) {
          clearTimeout(timerRef.current);
        }
      }}
      onDrop={(e) => {
        e.preventDefault();
        const files = e.dataTransfer.files;
        Array.from(files).forEach((file) => {
          uppy.addFile({
            name: file.name,
            data: file,
          });
        });
        setdragging(false);
      }}
    >
      {typeof children === 'function' ? children(dragging) : children}
    </div>
  );
}
